package com.sskj.aikeeper.hangqing.activity;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.base.IValueFormatter;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.sskj.aikeeper.R;
import com.sskj.aikeeper.bean.DataUtil;
import com.sskj.aikeeper.bean.Stock;
import com.sskj.aikeeper.presenter.ChartFragPresenter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.util.ScreenUtil;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/07/08
 */
@Route(path = RConfig.APP_FRAGMENT_CHART)
public class ChartFragment extends BaseFragment<ChartFragPresenter> {
    @BindView(R.id.chart_view)
    KChartView chartView;
    @Autowired
    String coinCode;
    @Autowired
    String coinGoods;
    @Autowired
    boolean coinIsMinute;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private KChartAdapter mAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_chart;
    }

    @Override
    public ChartFragPresenter getPresenter() {
        return new ChartFragPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        ARouter.getInstance().inject(this);

        chartView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white));
        chartView.setMinuteLineWidth((int) RudenessScreenHelper.dp2px(App.INSTANCE, 1));
        chartView.setBreathColor(ContextCompat.getColor(App.INSTANCE, R.color.lib_theme));
        chartView.getmCurrentLinePaint().setColor(ContextCompat.getColor(App.INSTANCE, R.color.lib_theme));
        chartView.getmCurrentPricePaint().setColor(ContextCompat.getColor(App.INSTANCE, R.color.lib_theme));
        chartView.showLoading();
        chartView.setDrawTabView(true);
        chartView.setMainUpColor(R.color.libUpColor);  // 设置k线颜色 涨
        chartView.setMainDownColor(R.color.libDownColor); // 设置k线颜色 跌
        chartView.setGridRows(4);
        chartView.setGridLineColor(ContextCompat.getColor(App.INSTANCE, R.color.color_f2));
        chartView.getmCurrentPricePaint().setTextSize(30);
        chartView.setShader(Color.parseColor("#9E735ee7"), Color.parseColor("#4E735ee7"), Color.parseColor("#00735ee7"), 1600);
        chartView.setGridColumns(4);
        chartView.setVolumeMaGone(true);
        if (coinIsMinute) {
            chartView.setDrawMinuteStyle(true);
            chartView.setDateTimeFormatter(new TimeFormatter());
        } else {
            if (!coinGoods.equals("day")) {
                chartView.setDateTimeFormatter(new DateLFormatter() {
                    @Override
                    public String format(Date date) {
                        return TimeFormatUtil.SF_FORMAT_D.format(date);
                    }
                });
            } else {
                chartView.setDateTimeFormatter(new DateLFormatter() {
                    @Override
                    public String format(Date date) {
                        return TimeFormatUtil.SF_FORMAT_K.format(date);
                    }
                });
            }
        }
        chartView.setVolumeMaGone(true);
        chartView.getmCurrentPricePaint().setTextSize(ScreenUtil.dp2px(getContext(), 12));
        chartView.setValueFormatter(new IValueFormatter() {
            @Override
            public String format(float v) {
                return NumberUtil.keep2(v);
            }
        });
        mAdapter = new KChartAdapter();
        chartView.setAdapter(mAdapter);

    }

    public KChartView getKChartView() {
        return chartView;
    }


    @Override
    public void initData() {
        mPresenter.getStockInfo(coinGoods, coinCode);
    }

    /**
     * 长链接  更新当前分时图
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals(coinCode) && mAdapter.getCount() > 0) {
            try {
                Stock lastItem = (Stock) mAdapter.getItem(mAdapter.getCount() - 1);
                long timeStamp = dateFormat.parse(data.getDate() + " " + data.getTime()).getTime();
                if (isAdd(timeStamp, lastItem.getTimestamp() * 1000)) {
//                    Stock stock = copyStock(data);
//                    List<Stock> stocks = new ArrayList<>();
//                    stock.setOpen(lastItem.getClosePrice());
//                    stock.setHigh(Double.valueOf(data.getPrice()));
//                    stock.setLow(Double.valueOf(data.getPrice()));
//                    stock.setVolume(lastItem.getVolume());
//                    mAdapter.getDatas().add(stock);
////                    DataUtil.calculate(stocks);
//                    mAdapter.changeLastItemClosePrice(Float.parseFloat(data.getPrice()));

//                    mAdapter.addNewData(stocks);
                    mPresenter.getStockInfo(coinGoods, coinCode);

                } else {
                    if (Double.valueOf(data.getPrice()) > lastItem.getHigh()) {
                        lastItem.setHigh(Double.valueOf(data.getPrice()));
                    }
                    if (Double.valueOf(data.getPrice()) < lastItem.getLow()) {
                        lastItem.setLow(Double.valueOf(data.getPrice()));
                    }
                    lastItem.setClose(Double.valueOf(data.getPrice()));
                    mAdapter.getDatas().set(mAdapter.getCount() - 1, lastItem);
                    mAdapter.changeLastItemClosePrice(Float.parseFloat(data.getPrice()));
//                mPresenter.getStockInfo(goodsType, code);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    public void getStockInfoOK(List<Stock> stockList) {
        if (stockList == null) {
            return;
        }
        if (chartView != null) {
            chartView.hideLoading();
            Collections.reverse(stockList);
            DataUtil.calculate(stockList);
            mAdapter.getDatas().clear();
            mAdapter.updateData(stockList);
        }
    }

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            return new Date(datas.get(position).getDate());
        }

        /**
         * 向头部添加数据
         */
        public void addNewData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyItemRangeInsertedToLast();
            }
        }


        /**
         * 向尾部添加数据
         */
        public void updateData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.clear();
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         */
        public void changeLastItemClosePrice(float closePrice) {
            notifyLastItemChanged(closePrice);
        }
    }


    public Stock copyStock(CoinBean newStock) {
        Stock stock = new Stock();
        try {
            long timeStamp = dateFormat.parse(newStock.getDate() + " " + newStock.getTime()).getTime();
            stock.setCode(newStock.getCode());
            stock.setClosePrice(Float.parseFloat(newStock.getClose()));
            stock.setTimestamp(timeStamp / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return stock;
    }


    private boolean isAdd(long newTime, long lastTime) {
        boolean add = false;
        newTime = newTime / 1000;
        lastTime = lastTime / 1000;
        long time = newTime - lastTime;
        if (coinGoods.equals("minute")) {
            add = time >= 1 * 60;
        } else if (coinGoods.equals("minute1")) {
            add = time >= 1 * 60;
        } else if (coinGoods.equals("minute5")) {
            add = time >= 5 * 60;
        } else if (coinGoods.equals("minute15")) {
            add = time >= 15 * 60;
        } else if (coinGoods.equals("minute30")) {
            add = time >= 30 * 60;
        } else if (coinGoods.equals("day")) {
            add = time >= 24 * 60 * 60;
        } else if (coinGoods.equals("minute240")) {
            add = time >= 4 * 60 * 60;
        }
        return add;
    }
}
